<?php
/**
 * User functions and profile management
 *
 * ACCESS: LOGGED IN USERS ONLY
 *
 * @author Chris Lunsford
 * @version 1.0
 */
class Users extends Controller {
	
	/**
	 * Class constructor
	 */
	function __construct() {
		parent::__construct();
		
		$this->badger->checkState();
		
		$this->load->model('UserModel');
	}
	
	/******************** URL Functions ********************/
	
	/**
	 * Displays a user's profile, if the logged in user is viewing their own profile
	 * a link to an edit page is shown
	 */
	function profile() {
		//grab the current user
		$user = $this->UserModel->getUserByName($this->session->userdata('username'));
		
		if ($this->uri->segment(3) == "edit") {
			//the user is wanting to edit their own profile
			$this->load->library('validation');
			
			$rules['firstname'] = "trim|required";
			$rules['lastname'] = "trim|required";
			$rules['email'] = "trim|required|valid_email";
			$this->validation->set_rules($rules);
			
			$fields['firstname']	= 'first name';
			$fields['lastname']	= 'last name';
			$fields['email'] = 'email address';
			$this->validation->set_fields($fields);
	
			$this->validation->set_error_delimiters('<div class="error">','</div>');
		
			if($this->validation->run() == FALSE) {
				$data = $this->_buildContent();		
				//then we need to let the current user edit their own profile
				$user->firstname = ($this->validation->firstname != NULL) ? $this->validation->firstname : $user->firstname;
				$user->lastname = ($this->validation->lastname != NULL) ? $this->validation->lastname : $user->lastname;
				$user->email = ($this->validation->email != NULL) ? $this->validation->email : $user->email;
				$data['user'] = $user;
				
				$this->load->view('users/profile_edit',$data);
			} else {
				$post['firstname'] = $this->input->post('firstname', TRUE);
				$post['lastname'] = $this->input->post('lastname', TRUE);
				$post['email'] = $this->input->post('email',TRUE);
				
				$this->UserModel->updateUser($user->userid,$post);			
				redirect('users/profile/'.$user->userid);
			}
		} elseif ($this->uri->segment(3) == "password") {
			//the user is wanting to change their password
			$this->load->library('validation');
			
			$rules['old_password'] = "trim|required|callback_validatePassword";
			$rules['new_password'] = "trim|required|matches[new_password_conf]";
			$rules['new_password_conf'] = "trim|required";
			$this->validation->set_rules($rules);
			
			$fields['old_password']	= 'old password';
			$fields['new_password']	= 'new password';
			$fields['new_password_conf'] = 'confirm new password';
			$this->validation->set_fields($fields);
	
			$this->validation->set_error_delimiters('<div class="error">','</div>');
		
			if($this->validation->run() == FALSE) {
				$data = $this->_buildContent();		
				$this->load->view('users/profile_change_password',$data);
			} else {
				$new_password = $this->input->post('new_password', TRUE);
				
				$post = array();
				//need to make updates based on salting.
				if ($user->salt == NULL) {
					//no salt...just update the password and allow salting to update on their next login
					$post['password'] = sha1($new_password);
				} else {
					//salt the password and update the database
					$post['password'] = sha1($new_password.$user->salt);
				}
				
				$this->UserModel->updateUser($user->userid,$post);			
				$this->session->set_flashdata('msg_info','Your password has been succesfully updated.');
				redirect('users/profile/'.$user->userid);
			}
		} else {
			$data = $this->_buildContent();
			//we're just viewing the user's profile
			$data['user'] = $this->UserModel->getUser($this->uri->segment(3));
			$data['groups'] = $this->UserModel->getGroupDescriptionsForUser($this->uri->segment(3));
			$data['edit'] = ($user->userid == $this->uri->segment(3)) ? '(<a href="'.site_url().'users/profile/edit">edit</a>)' : '';
			$data['gravatar'] = 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($data['user']->email);

			$this->load->view('users/profile', $data);
		}
	}
	
	
	/******************* Task Functions *******************/

	/*
	 * Callback function to make sure the old password supplied is the user's current password
	 * @param password the password being supplied for testing
	 * @return whether the password is correct or not
	 */
	function validatePassword($password) {
		$user = $this->UserModel->getUserByName($this->session->userdata('username'));
		if (!$this->UserModel->validateLogin($this->session->userdata('username'),$password)) {
			$this->validation->set_message('validatePassword', 'The old password supplied is not the current password for this account.  Please supply the current password.');
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	/*
	 * Supplies user-specific information to the interface for customization
	 *
	 */
	function _buildContent() {
		//REQUIRED//
		$data['sidebar'] = TRUE;
		if ($this->session->flashdata('msg_info')) $data['msg_info'] = $this->session->flashdata('msg_info');
		if ($this->session->flashdata('msg_error'))	$data['msg_error'] = $this->session->flashdata('msg_error');
				
		//test if user is logged in for site navigation
		if ($this->session->userdata('loggedin')) {
			$data['loggedin'] = TRUE;
			
			//grab the user
			$user = $this->UserModel->getUserByName($this->session->userdata('username'));
			$user->display = $this->UserModel->getDisplayName($user->userid);
			//test for identity swap mystery
			log_message('info','Generated sidebar content. Username: '.$user->username.' Session: '.$this->session->userdata('username').'.');
		
			$data['con_user'] = $user;
			
			//is admin?
			if ($this->UserModel->isUserInGroup($user->userid,$this->UserModel->getGroupID('admin'))) {
				$data['links'] = '<a  href="'.site_url("admin").'">admin</a> | <a href="'.site_url("site/logout").'">logout</a>';
			} else {
				$data['links'] = '<a href="'.site_url("site/logout").'">logout</a>';
			}
		}
		
		return $data;
	}
}
?>